<template>
  <div>
    <!-- 当一个组件绑定很多属性 方法指令的时候
    顺序是 先写指令 v-model v-for v-if
    在写属性 :aaa bbb :ccc
    最后写方法 @change @click @load -->
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
    <van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"
  offset='50'
  :immediate-check='false'
  @load="onLoad"
>
    <!-- 文章列表 -->
    <article-item v-for='item in articleList' :key='item.art_id' :Obj='item'></article-item>
</van-list>
</van-pull-refresh>
    <!-- <article-item></article-item>
    <article-item></article-item> -->
  </div>
</template>

<script>
import { timeAgo } from '@/utils/date.js'
import { articlesListAPI } from '@/api'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  props: {
    // 从父组件接收的频道id
    cid: Number
  },
  components: {
    ArticleItem
  },
  created () {
    this.getArticleList()
  },
  data () {
    return {
      articleList: [],
      loading: false,
      finished: false,
      nextTime: null,
      isLoading: false
    }
  },
  methods: {
    // 获取文章
    async getArticleList () {
      const res = await articlesListAPI({
        channelId: this.cid,
        timestamp: this.nextTime
      })

      // 数据处理
      res.data.data.results.forEach(item => {
        item.pubdate = timeAgo(item.pubdate)
      })
      // this.articleList = res.data.data.results
      console.log(this.nextTime)
      console.log(res.data.data)

      // 1.判断当前返回的结果是不是长度为0
      // 如果长度为0说明请求完了
      // 此时需要将组件中的finished设为true

      // 2.如果此时返回值结果是有长度的
      // 对nextTime进行赋值
      // 将返回的结果和之前的数组进行合并拼接 ... es6语法展开运算符
      // 将loading状态改为false

      // 滚动加载文章
      if (res.data.data.results.length === 0) {
        this.finished = true
      } else {
        this.nextTime = res.data.data.pre_timestamp // 保存下一页数据的时间(做分页用)
        this.articleList = [...this.articleList, ...res.data.data.results]
        this.loading = false
      }
    },
    onLoad () {
      // console.log('触发底部加载')
      if (this.articleList.length > 0) {
        this.getArticleList()
      }
    },
    onRefresh () {
      // 下拉刷新
      this.nextTime = null
      this.articleList = []
      this.getArticleList()
      this.isLoading = false
    }
  }
}
</script>
